package com.gulimall.search.service.imp;

import com.alibaba.nacos.common.utils.JacksonUtils;
import com.gulimall.search.constant.EsConstant;
import com.gulimall.search.service.ProductSaveService;
import com.zlc.common.to.es.SkuEsModel;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductSaveServiceImp implements ProductSaveService {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Override
    public boolean upProduct(List<SkuEsModel> skuEsModels) throws IOException {
        //1.建立索引
        //此处已经直接通过postman创建索引了

        //2.保存到ES
//        两个参数   BulkRequest bulkRequest, RequestOptions options
        BulkRequest bulkRequest = new BulkRequest();

        for (SkuEsModel model : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId().toString());
            String s = JacksonUtils.toJson(model);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }

        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        boolean b = bulkResponse.hasFailures();
        //如果批处理出错  简单日志打印
        if(b){
            BulkItemResponse[] items = bulkResponse.getItems();
            List<String> collect = Arrays.stream(items).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.info("商品上架错误,{}",collect);
        }

        return b;
    }
}
